<?php
namespace Home\Controller;
use Common\Lib\User;
use Home\Model\DepartmentModel;
use Home\Model\RoleModel;

class EmployeeActivityController extends CommonController {
	protected $table="EmployeeActivity";
	protected $pageSize = 13;


	public function index (){
		$D = D('RbacUser');
		 //获取所有CRM部门 (一维)
        $getalldepartmentsList_url = "Department/getAllDepartmentsList";
	    $alldepartmentsList = json_decode(http_get($getalldepartmentsList_url),true);
        //获取所有CRM部门 (二维)
        $getalldepartments_url = "Department/getAllDepartments";
	    $alldepartments = json_decode(http_get($getalldepartments_url),true);

		$this->assign("roleList", $this->getRoles());
		$this->assign("groupList", D('Group')->where(array('status'=>1))->select());
		$this->assign("sexType", array("未定义", "男", "女"));
		$ename = $this->getRoleEname();
		/*echo 'sss';
		print_r($ename);
		echo 'kkk';*/
    	$this->assign('viewDecorator', D("Department")->decoratorView($ename));

    	//部门选项权限
    	$ename=$this->getRoleEname();

      
    	$this->assign('depart_id', $this->getDepartmentId());
    	$this->assign('departmentItem', $this->setEmployeeDepartemtnItem());
    	$this->assign('allRoles', D('Role')->getField('id,name', true));
       /* 我加的 开始*/
    	$this->assign("userNames", D("User")->getUserNames());
    	$this->assign("departmentNames", D("Department")->getDepartmentsNames());
    	$this->assign("sexType", array("未定义", "男", "女"));
    	$this->assign("sourcesType", array("1"=>"58同城", "2"=>"赶集", "3"=>"智联", "4"=>"前程", "5"=>"校招", "6"=>"介绍", "7"=>"其他"));
    	$this->assign('departments', D('Department')->getAllDepartments('id,name'));
    	$this->assign("sourcesList", $D->getSources());
    	$this->assign('user_role_id', session('account')['userInfo']['role_id']);
    	//获取crm的部门，职能 start
    	$this->assign('allDepartmentsList',$alldepartmentsList["list"]);//一维
    	$this->assign('allDepartments',$alldepartments["list"]);//二维
    	/* 我加的 结束*/
		$this->display();
	}

	public function setQeuryCondition() {
		$department_id = I('get.department_id');
		$user_id = session('account')['userInfo']['user_id'];
		$date = I('get.date');
			switch(session('account')['userInfo']['role_id']){
				case 18:
				if(!empty($department_id)){
					$this->M->where(array('department_id'=>$department_id))->order("id desc");
				}else{
					$this->M->order("id desc");
				}
			    break;
			    default :
			    $this->M->where(array('department_id'=>session('account')['userInfo']['department_id'],'user_id'=>$user_id))
			        ->order("id desc");
			}
			if (isset($_GET['name'])) {
			$this->M->where(array('name'=>array('like', I('get.name')."%")));
		    }
		    if (isset($_GET['date'])) {
			$this->M->where(array('date'=>$date));
		    }

	}

	private function getDepartmentRow(){
		if (!isset($this->departmentRow)) {
			$this->departmentRow = D('Department')->find($this->getDepartmentId());
		}
		return $this->departmentRow;
	}

	private function isHrDeparment(){
		$this->getDepartmentRow();
		
		if ($this->departmentRow['type'] == DepartmentModel::HR_DEPARTMENT) {
			return true; //$_POST['department_id'] = 0;
		} else {
			return false; //$_POST['department_id'] = session('account')['userInfo']['department_id'];
		}
	}

	private function getDepartmentId(){
		// var_dump(session('account')['userInfo']['department_id']);
		if ($this->getRoleEname()=='gold') {
			return 0;
		} else {
			$depart_id = session('account')['userInfo']['department_id'];
			
			if ($depart_id == 0) {
				return 9999999;
			} else {
				return $depart_id;
			}
		}
		
	}

	

	private function setDeparmentQuery(){
		$departmentRow = $this->getDepartmentRow();
		$config = json_decode($departmentRow['config'], true);
		if (isset($config['EmployeeQueryCondition'])) {

			call_user_func(array($this, 'set'.$config['EmployeeQueryCondition']));
		}
	}



	private function setDepartmentEmployee(){
		
		$this->M->where(array(
			'user_info.department_id'=>array('eq', $this->getDepartmentId()),
			// 'role_id'=>array('NEQ', array()) 
		));

	}
	private function setAllEmployee(){
		
	}
	// 
	private function goldCondition(){
		$this->setAllEmployee();
	}

	//人事
	private function humanResourceCondition(){

		if ($this->isHrDeparment()) {
			$this->setAllEmployee();
		} else {
			$this->setDeparmentQuery();
		}
		
	}

	//人事经理
	private function hrMasterCondition(){
		$this->setAllEmployee();
	}

	//风控经理
	private function riskMasterCondition(){
		$this->setDepartmentEmployee();
	}
	//客服经理
	private function serviceMasterCondition(){
		$this->setDepartmentEmployee();
	}



	//部门经理
	private function departmentMasterCondition(){
		$this->setDepartmentEmployee();
	}


	public function setRoleCondition(){
		$this->roleEname = $this->getRoleEname();
        $funcName = $this->roleEname."Condition";
        if (method_exists($this, $funcName)) {
             call_user_func(array($this, $funcName));
        } else {
        	$this->error("没有权限EmployeeController");
        }
	}

	



	public function getRoles(){
		/*$row = M('rbac_role')->field('level')->find(session('account')['userInfo']['role_id']);
		return D('rbac_role')->where(array('level'=>array('gt', $row['level'])))->select();*/
		$departRow = D("Department")->find(session('account')['userInfo']['department_id']);
		if ($departRow) {
			return D("Department")->getEmployeeRoles($departRow['type']);
		} else {
			return D('rbac_role')->select();
		}
		
	}


	/**
	* 获取用户 角色 id
	*
	*/
	public function getUserRoles(){
		$result = D('rbac_role_user')->where(array('user_id'=> I('get.user_id',0)))->select();
		$this->ajaxReturn($result);
	}

	/**
	* 设置用户 角色 id
	*/
	public function setUserRoles(){
		$M = D('rbac_role_user');
		$user_id = I('post.user_id',0);
		$role_ids = I('post.role_ids');
		$insert_list = array();
		if (is_array($role_ids)) {
			foreach ($role_ids as $value) {
				$insert_list[] = array('role_id'=>$value, 'user_id'=>$user_id);
			}
		} else {
			$insert_list[] = array('role_id'=>$role_ids, 'user_id'=>$user_id);
		}
		
		$M->startTrans(); 
		$result = $M->where(array('user_id'=>$user_id))->delete();

		if ($result !== false) {
			$insert_result = $M->addAll($insert_list);
			if ($insert_result !== false) {
				$re = M('user_info')->data(array('user_id'=>$user_id, 'role_id'=>$role_ids))->save();
				if ($re !== false) {
					$M->commit();
					$this->success("操作成功");
				} else {
					$M->rollback();
					$this->error("操作失败".M('user_info')->getError());
				}
				
			} else {
				$M->rollback();
				$this->error("操作失败".$M->getError());
			}
		} else {
			$M->rollback();
			
			$this->error("操作失败".$M->getError());
		}
	}

	/**
	* 预处理
	*/
	public function _before_add(){
		$this->rightProcted();	
	}

	/**
	* 添加
	*/
	public function add(){
		$_POST["time"] = empty($_POST["time"])?"":UTC_to_locale_time($_POST["time"]);
		$_POST['department_id'] = session('account')['userInfo']['department_id'];
		$_POST['user_id'] = session('account')['userInfo']['user_id'];
		if(empty($_POST["time"])){
			$this->error("请选择日期时间！");
			exit();
		}
		$_POST["date"] = substr($_POST["time"],0,10);
		//员工培训，员工活动，员工面谈暂时不限制是否重复
	/*	if(add_field_unique("employee_activity",session('account')['userInfo']['department_id'],"name",$_POST["name"])){
			$this->error("该活动名称已录入！");
			exit();
		}*/
		$new2 =array();
		foreach($_POST["file_url"] as $kk=>$vv){
				array_push($new2,$vv["file_realname"]);
		}
		foreach($_POST["alladdfiles"] as $kkk=>$vvv){
			if(!in_array($vvv["file_realname"],$new2)){
				$_POST["file_realname"] =  $vvv["file_realname"];
				$_POST["path"] =  $vvv["file_path"];
			}else{
				unlink(".".$vvv["file_path"]);
			}
		}
		$re = $this->M->create($_POST, 1);
		if ($re) {
			$this->M->startTrans(); 
			$re['emplyeeActivity'] = M('EmployeeActivity')->create($_POST, 1);
			$id = $this->M->add($re);
			if ($id) {
					$this->M->commit();
					$this->success(L('ADD_SUCCESS'));
			} else {
				$this->M->rollback();
				$this->error($this->M->getError());
			}
		} else {
			$this->error($this->M->getError());
		}

	}



	/**
	* 编辑
	*/
		public function edit(){
		//新方法
		$_POST["time"] = $_POST["time"] == "0000-00-00"?"":UTC_to_locale_time($_POST["time"]);
		if($_POST['department_id']!=0){
		   $_POST['department_name'] =D("Department")->getDepartment($_POST['department_id']);		
		}
		if(empty($_POST["time"])){
			$this->error("请选择日期时间！");
			exit();
		}
		$_POST["date"] = substr($_POST["time"],0,10);
		//员工培训，员工活动，员工面谈暂时不限制是否重复
      /*  if(edit_field_unique("employee_activity",$_POST["department_id"],"name",$_POST["name"],$_POST["id"])){
			$this->error("该活动名称已录入！");
			exit();
		}*/
		$_POST["path"] = $_POST["head"];
		$_POST["file_realname"] = $_POST["file_realname"];
        $re = M('employeeActivity')->create($_POST, 2);
		if ($re) {
			if (M('employeeActivity')->where(array('id'=>I('post.id') ))->save() !== false) {
				$this->success(L('ADD_SUCCESS'));
			} else {
				$this->error($this->M->getError().$this->M->getLastSql());
			}
		} else {
			$this->error($this->M->getError().$this->M->getLastSql());
		}

	}


	public function changePassword(){
		$re = $this->M->create($_POST, 2);
		if ($re) {
			if ($this->M->save() !== false) {
				$this->success(L('ADD_SUCCESS'));
			} else {
				$this->error($this->M->getError().$this->M->getLastSql());
			}
		} else {
			$this->error($this->M->getError().$this->M->getLastSql());
		}
	}

	public function setEmployeeDepartemtnItem(){
		if ($this->getRoleEname()=='gold') {
			return 1;
		} else if(session('account')['userInfo']['department_id']!=0){
			$row = $this->getDepartmentRow();
			if ($row['type']==DepartmentModel::HR_DEPARTMENT) {
				return 1;
			} 
		}
		return 0;
	}
	public function download(){
		$filename = $_GET["url"];
		$file_realname = $_GET["file_realname"];
	   $filename =".".$filename; 
	   $extention=substr(strrchr($filename,'.'),1);//获取后缀eg:doc
	    header("content-type:application/msword");
	    header("Content-type:application/octet-stream");//设置文件下载类型，以文件流的方式下载  
        header("Accept-Ranges:byte");//指定文件大小的格式 
	    //3.执行下载的文件名，设定配置
	    header("content-disposition:attachment;filename=".$file_realname.'.'.$extention);
	    //4.指定文件的大小
	    header("content-length:".filesize($filename));
	    //5.读取文件内容
        /*echo file_get_contents("1.txt", "r");*/
        echo file_get_contents($filename, "r");
        //6防止读取的内容中中文出现乱码的情况，可以用ob_clean()和flush()这两个函数。
        ob_clean();  
        flush(); 
	}



}
